package org.strongme.modules.project.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.strongme.common.web.BaseController;
import org.strongme.modules.project.entity.*;
import org.strongme.modules.project.service.*;
import org.strongme.modules.project.util.WordDocGenerator;
import org.strongme.modules.sys.utils.DictUtils;
import org.strongme.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("project/report")
public class ReportController extends BaseController{
	@Autowired
	private ProjectService projectService;
	@Autowired
	private SubProjectService subProjectService;
	@Autowired
	private OpGuideService opGudeService;
	@Autowired
	private TzService tzService;
	@Autowired
	private FyService fyService;
	
	private static final Integer PAGE_ONE_COUNT = 22;
	
	@RequestMapping(value = "exportMainReport")  
	public void exportMainReport(
			@RequestParam String projectId,
			@RequestParam String subProjectId,
			@RequestParam String ogId, 
			@RequestParam String gxh,
			@RequestParam String gg,
//			@RequestParam String sxy,
			@RequestParam String num,
//			@RequestParam String jcbl,
//			@RequestParam String hgjb,
//			@RequestParam String cz,
			@RequestParam String dates,
			final HttpServletResponse response) {  
		OutputStream outputStream = null;
		Project project = projectService.get(new Project(projectId));
		SubProject subProject = subProjectService.get(new SubProject(subProjectId));
		OpGuide opGuide = opGudeService.get(new OpGuide(ogId));
		Tz tz=  new Tz();
		tz.setSubProject(new SubProject(subProjectId));
		tz.setGg(gg);tz.setGxh(gxh);
		//增加检测比例和合格级别的筛选
//		tz.setJcbl(jcbl);
//		tz.setHgjb(hgjb);
//		tz.setCz(cz);
//		tz.setSxy(sxy);
		List<Tz> tzList = tzService.findListBySub_GXH_GG(tz);
		
		Fy fyForSearch = new Fy();
		fyForSearch.setProject(new Project(projectId));
		fyForSearch.setSubProject(new SubProject(subProjectId));
		fyForSearch.setJjbh(gxh);
		fyForSearch.setGg(gg);
		List<Fy> fyList = fyService.loadFyByGx_GG_Pro_Sub(fyForSearch);
		
		if(project==null||subProject==null||opGuide==null||tzList==null||tzList.size()==0||fyList==null||fyList.size()==0) {
			try {
				response.getWriter().write("Export Failed, No Data");
			} catch (IOException e) {
				//e.printStackTrace();
			}
		}else {
			Map<String, String> data = rendererMainMap(project, opGuide, subProject, tzList, fyList);
			String bgbh = project.getSuoxie()+"-"+subProject.getSuoxie()+"-RTBG";
			String jlbh = project.getSuoxie()+"-"+subProject.getSuoxie()+"-RTJL";
			data.put("bgbh", bgbh+"-"+num);
			data.put("jlbh", getJLBH(tzList));
			data.put("dates", dates);
			if(fyList.size()<=PAGE_ONE_COUNT) {
				data.put("totalPage", "2");
			}else {
				int yushu = fyList.size()%PAGE_ONE_COUNT;
				int result = fyList.size()/PAGE_ONE_COUNT+1;
				if(yushu!=0)result+=1;
				data.put("totalPage", String.valueOf(result));
			}
			try {
				String fileName = bgbh+"-"+new String(("主").getBytes("gbk"),"iso8859-1")+"-"+num+".doc";
				response.reset();  
				response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");  
				response.setContentType("application/msword;charset=UTF-8");  
				outputStream = new BufferedOutputStream(response.getOutputStream());
				WordDocGenerator.createDoc(data, "report_main", outputStream);
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				if(outputStream!=null) {
					try {
						outputStream.flush();
						outputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}  
		}
		
	}  
	
	private String getJLBH(List<Tz> tzList) {
		HashSet<String> sets = Sets.newHashSet();
		for(Tz t : tzList) {
			sets.add(t.getXh());
		}
		List<String> jlbhs = Lists.newArrayList(sets);
		List<String> resultNum =Lists.newArrayList();
		for(String s : jlbhs) {
			if(StringUtils.isBlank(s))continue;
			resultNum.add(s.substring(s.lastIndexOf("-")+1, s.length()));
		}
		Collections.sort(resultNum);
		String nums = StringUtils.join(resultNum, "、");
		String prefix = jlbhs.get(0);
		prefix = prefix.substring(0, prefix.lastIndexOf("-")+1);
		prefix = prefix + nums;
		return prefix;
	} 
	
	private String nullThenEmptyStr(String t) {
		if(t==null) {t="";}
		t = t.replaceAll("\\+", "\u002B");
		t = t.replaceAll("\\-", "\u002d");
		t = t.replaceAll("&plusmn;", "\u00b1");
		t = t.replaceAll("x", "\u0078");
		t = t.replaceAll("/", "\u002f");
		t = t.replaceAll("&Phi;", "\u03a6");
		t = t.replaceAll("&times;", "\u00d7");
		return t;
	}
	
	private Map<String, String> rendererMainMap(Project project, OpGuide opGuide, SubProject subProject,List<Tz> tzList, List<Fy> fyList) {
		Map<String, String> result = Maps.newHashMap();
		result.put("wtdw", nullThenEmptyStr(project.getClient()));
		result.put("gcmc", nullThenEmptyStr(project.getName()));
		result.put("cysblb", DictUtils.getDictLabel(nullThenEmptyStr(project.getCysblb()), "dict_cysblb", ""));
		
		result.put("dwgc", nullThenEmptyStr(subProject.getName()));
		result.put("jcbz", nullThenEmptyStr(subProject.getJcbz()));
		
		result.put("jpgg", nullThenEmptyStr(opGuide.getJpgg()));
		result.put("zdsbh", nullThenEmptyStr(opGuide.getCzzdsbh()));
		result.put("pkxs", DictUtils.getDictLabel(nullThenEmptyStr(opGuide.getPkxs()), "dict_pkxs", ""));
		result.put("hjff", nullThenEmptyStr(opGuide.getHjff()));
		result.put("rclzt",   DictUtils.getDictLabel(nullThenEmptyStr(opGuide.getRclzt()), "dict_rclzt", ""));
		result.put("ysgf", nullThenEmptyStr(opGuide.getYsgf()));
		result.put("jcbl", DictUtils.getDictLabel(nullThenEmptyStr(opGuide.getJcbl()), "dict_jcbl", "")  );
		result.put("jcsj", DictUtils.getDictLabel(nullThenEmptyStr(opGuide.getJcsj()), "dict_jcsj", "")  );
		result.put("jsdj", DictUtils.getDictLabel(nullThenEmptyStr(opGuide.getJsdj()), "dict_jsdj", "")  );
		result.put("hgjb", DictUtils.getDictLabel(nullThenEmptyStr(opGuide.getHgjb()), "dict_hgjb", "")  );
		result.put("bmzk", "合格");
		result.put("jcbw", "对接焊缝");
		result.put("tzjs", DictUtils.getDictLabel(nullThenEmptyStr(opGuide.getTzjs()), "dict_tzjs", "") );
		result.put("tzfs", DictUtils.getDictLabel(nullThenEmptyStr(opGuide.getTzfs()), "dict_tzfs", "") );
		result.put("syzl", DictUtils.getDictLabel(nullThenEmptyStr(opGuide.getYzl()), "dict_yzl", "") );
		result.put("yqxh", nullThenEmptyStr(opGuide.getYqxh()));
		result.put("jdcc", nullThenEmptyStr(DictUtils.getDictLabel(opGuide.getJdcc(), "dict_jdcc", "")));
		result.put("gdl", nullThenEmptyStr(opGuide.getGdl()));
		result.put("bgsj", nullThenEmptyStr(opGuide.getBgsj())+"min");
		result.put("gdy", nullThenEmptyStr(opGuide.getGdy()));
		result.put("jj", nullThenEmptyStr(opGuide.getJj()));
		result.put("gjzjpjl", nullThenEmptyStr(opGuide.getGjzjpjl()));
		result.put("syzgjjl", nullThenEmptyStr(opGuide.getSyzgjjl()));
		result.put("xzjfz", DictUtils.getDictLabel(nullThenEmptyStr(opGuide.getXzjwz()), "dict_xzjwz", ""));
		result.put("xzjxh", nullThenEmptyStr(opGuide.getXzjxh()));
		result.put("xzjlmd", nullThenEmptyStr(opGuide.getXzjlmd()));
		result.put("jpdj", nullThenEmptyStr(opGuide.getJpjdj()));
		result.put("zgp", nullThenEmptyStr(opGuide.getZgp()));
		result.put("hdfw", DictUtils.getDictLabel(nullThenEmptyStr(opGuide.getHdfw()), "dict_hdfw", "") );
		result.put("cxfs",  DictUtils.getDictLabel(nullThenEmptyStr(opGuide.getCxfs()), "dict_cxfs", "") );
		result.put("xytj", nullThenEmptyStr(opGuide.getXytj()));
		
		if(tzList==null) tzList=Lists.newArrayList();
		Tz tz = null;
		if(tzList.size()>0) {
			tz = tzList.get(0);
		}else {
			tz = new Tz();
		}
		result.put("gxbh", nullThenEmptyStr(tz.getGxh()));
		result.put("gg", nullThenEmptyStr(tz.getGg()));
		result.put("jjmc", nullThenEmptyStr(tz.getJjmc()));
		result.put("jjcz", nullThenEmptyStr(tz.getCz()));
		
		Integer jcsl = tzList.size();
		Integer level1Count = 0;
		Integer level2Count = 0;
		Integer level3Count = 0;
		Integer level4Count = 0;
		Integer ycfx = 0;
		Integer ecfx = 0;
		Integer kt = 0;
		if(fyList==null)fyList = Lists.newArrayList();
		Integer zps = fyList.size();
		Integer hgps = 0;
		Integer fxps = 0;
		
		String hgjbOG = opGuide.getHgjb();
		
		Map<String,List<Fy>> groupByHk = Maps.newHashMap();
		
		for(Fy fy : fyList) {
			if(fy!=null) {
				//分组
				String hkNow = fy.getHkbh();
				List<Fy> tmpFyList = groupByHk.get(hkNow);
				if(tmpFyList==null)tmpFyList=Lists.newArrayList();
				tmpFyList.add(fy);
				groupByHk.put(hkNow, tmpFyList);
				//评定结果
				if(fy.getPdjg()!=null&&!"".equals(fy.getPdjg())) {
					if("1".equals(fy.getPdjg())) {
						level1Count+=1;
					}else if("2".equals(fy.getPdjg())) {
						level2Count+=1;
					}else if("3".equals(fy.getPdjg())) {
						level3Count+=1;
					}else if("4".equals(fy.getPdjg())) {
						level4Count+=1;
					}
				}
				
				String hgjbThis = fy.getPdjg();
				if(hgjbOG!=null&&!"".equals(hgjbOG)&&hgjbThis!=null&&!"".equals(hgjbThis)) {
					if("4".equals(hgjbOG)) {
						if("4".equals(hgjbThis)||"3".equals(hgjbThis)||"2".equals(hgjbThis)||"1".equals(hgjbThis)) {
							hgps+=1;
						}
					}else if("3".equals(hgjbOG)) {
						if("3".equals(hgjbThis)||"2".equals(hgjbThis)||"1".equals(hgjbThis)) {
							hgps+=1;
						}
					}else if("2".equals(hgjbOG)) {
						if("2".equals(hgjbThis)||"1".equals(hgjbThis)) {
							hgps+=1;
						}
					}else if("1".equals(hgjbOG)) {
						if("1".equals(hgjbThis)) {
							hgps+=1;
						}
					}
				}
			}
		}
		fxps = zps-hgps;
		
		//返修情况汇总
		for(String key : groupByHk.keySet()) {
			List<Fy> fyTmpList = groupByHk.get(key);
			if(fyTmpList!=null&&fyTmpList.size()>0) {
				boolean hasYcfx = false;
				boolean hasEcfx = false;
				for(Fy fy : fyTmpList) {
					if(fy!=null) {
						String ph = fy.getPh();
						if(ph!=null) {
							if(ph.contains("R1")) {
								hasYcfx = true;
							}else if(ph.contains("R2")) {
								hasEcfx = true;
							}
						}
					}
				}

				//有R1没R2算一次返修
				if(hasYcfx && !hasEcfx)ycfx += 1;
				//有R2的算二次返修,忽略一次返修
				if(hasEcfx)ecfx += 1;

				for(Fy fy : fyTmpList) {
					if(fy!=null) {
						//焊口编号
						String hkbh = fy.getHkbh();
						if(hkbh!=null&&hkbh.contains("K")) {
							kt+=1;
							break;
						} 
					}
				}
			}
		}
		
		
		Integer fxgj = ycfx+ecfx;
		Integer zgfx = 0;
		if(ycfx==0&&ecfx==0) {
			zgfx = 0;
		}else if(ycfx>0&&ecfx==0) {
			zgfx = 1;
		}else if(ecfx>0) {
			zgfx = 2;
		}
		
		result.put("fxgj", String.valueOf(fxgj));
		result.put("zgfx", String.valueOf(zgfx));
		result.put("level1Count", String.valueOf(level1Count));
		result.put("level2Count", String.valueOf(level2Count));
		result.put("level3Count", String.valueOf(level3Count));
		result.put("level4Count", String.valueOf(level4Count));
		result.put("jcsl", String.valueOf(jcsl));
		result.put("ycfx", String.valueOf(ycfx));
		result.put("ecfx", String.valueOf(ecfx));
		result.put("kt", String.valueOf(kt));
		result.put("zps", String.valueOf(zps));
		result.put("hgps", String.valueOf(hgps));
		result.put("fxps", String.valueOf(fxps));
		
		return result;
	}
	
	@RequestMapping(value = "exportViceReport")  
	public void exportViceReport(
			@RequestParam String projectId,
			@RequestParam String subProjectId,
			@RequestParam String gxh,
//			@RequestParam String sxy,
			@RequestParam String num,
			@RequestParam String gg,
			final HttpServletResponse response) {  
		OutputStream outputStream = null;
		Project project = projectService.get(new Project(projectId));
		SubProject subProject = subProjectService.get(new SubProject(subProjectId));
		
		Tz tz=  new Tz();
		tz.setSubProject(new SubProject(subProjectId));
		tz.setGg(gg);tz.setGxh(gxh);
		List<Tz> tzList = tzService.findListBySub_GXH_GG(tz);
		
		Fy fy = new Fy();
		fy.setProject(project);
		fy.setSubProject(subProject);
		fy.setJjbh(gxh);
		fy.setGg(gg);
		List<Fy> fyList = fyService.findBySubGxh(fy);
		
		if(project==null||subProject==null||fyList==null||fyList.size()==0||tzList==null||tzList.size()==0) {
			try {
				response.getWriter().write("Export Failed, No Data");
			} catch (IOException e) {
				//e.printStackTrace();
			}
		}else {
			Map<String, Object> data = rendererViceMap(project, subProject, fyList);
			String bgbh = project.getSuoxie()+"-"+subProject.getSuoxie()+"-RTBG";
			String jlbh = getJLBH(tzList);
			data.put("bgbh", bgbh+"-"+num);
			data.put("jlbh", jlbh);
			try {
				String fileName = bgbh+"-"+new String(("附").getBytes("gbk"),"iso8859-1")+"-"+num+".doc";
				response.reset();  
				response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");  
				response.setContentType("application/msword;charset=UTF-8");  
				outputStream = new BufferedOutputStream(response.getOutputStream());
				WordDocGenerator.createDoc(data, "report_vice", outputStream);
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				if(outputStream!=null) {
					try {
						outputStream.flush();
						outputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}  
		}
		
	}
	
	private Map<String, Object> rendererViceMap(Project project,SubProject subProject,List<Fy> fyList)  {
		Map<String, Object> result = Maps.newHashMap();
		result.put("wtdw", nullThenEmptyStr(project.getClient()));
		result.put("gcmc", nullThenEmptyStr(project.getName()));
		
		result.put("dwgc", nullThenEmptyStr(subProject.getName()));
		Fy fy = fyList.get(0);
		result.put("gxbh", nullThenEmptyStr(fy.getJjbh()));
		result.put("jjmc", nullThenEmptyStr(fy.getJjmc()));
		List<Map<String, String>> hkList = Lists.newArrayList();
		for(int i=0;i<fyList.size();i++) {
			Fy t = fyList.get(i);
			Map<String, String> tMap = Maps.newHashMap();
			tMap.put("hkbh", nullThenEmptyStr(t.getHkbh()));
			tMap.put("ph", nullThenEmptyStr(t.getPh()));
			tMap.put("gg", nullThenEmptyStr(t.getGg()));
			tMap.put("hgh",nullThenEmptyStr( t.getHgh()));
			tMap.put("qxxz",nullThenEmptyStr( t.getQxxz()));
			tMap.put("qxdl", nullThenEmptyStr(t.getQxdl()));
			tMap.put("pdjg", DictUtils.getDictLabel(nullThenEmptyStr(t.getPdjg()), "dict_fy_pdjg", "") );
			tMap.put("bz", nullThenEmptyStr(t.getRemarks()));
			hkList.add(tMap);
		}
		List<List<Map<String, String>>> seprateFyList = Lists.newArrayList();
		if(hkList.size()<=PAGE_ONE_COUNT) {
			//小于固定的一页条数
			int need = PAGE_ONE_COUNT-hkList.size();
			for(int i=0;i<need;i++) {
				Map<String, String> tMap = Maps.newHashMap();
				tMap.put("hkbh", "");
				tMap.put("ph", "");
				tMap.put("gg", "");
				tMap.put("hgh","");
				tMap.put("qxxz","");
				tMap.put("qxdl", "");
				tMap.put("pdjg", "");
				tMap.put("bz", "");
				hkList.add(tMap);
			}
			seprateFyList.add(hkList);
		}else {
			//大于固定的一页条数
			List<Map<String, String>> tmphkList = Lists.newArrayList();
			for(int i=0;i<hkList.size();i++) {
				if(tmphkList.size()==PAGE_ONE_COUNT){
					seprateFyList.add(tmphkList);
					tmphkList = Lists.newArrayList();
				}
				tmphkList.add(hkList.get(i));
			}
			if(tmphkList.size()>0&&tmphkList.size()<=PAGE_ONE_COUNT) {
				int need = PAGE_ONE_COUNT-tmphkList.size();
				for(int i=0;i<need;i++) {
					Map<String, String> tMap = Maps.newHashMap();
					tMap.put("hkbh", "");
					tMap.put("ph", "");
					tMap.put("gg", "");
					tMap.put("hgh","");
					tMap.put("qxxz","");
					tMap.put("qxdl", "");
					tMap.put("pdjg", "");
					tMap.put("bz", "");
					tmphkList.add(tMap);
				}
				seprateFyList.add(tmphkList);
			}
		}
		result.put("hkListMap", seprateFyList);
		return result;
	}
	
	
	
	
	@RequestMapping("mainReport")
	public String mainReport(Model model) {
		model.addAttribute("projectList", projectService.findList(new Project()));
		return "modules/project/report/mainReport.jsp";
	}
	
	@RequestMapping("subReport")
	public String subReport(Model model) {
		model.addAttribute("projectList", projectService.findList(new Project()));
		return "modules/project/report/viceReport.jsp";
	}

	@RequestMapping("loadCzByProject")
	@ResponseBody
	public Map<String, Object> loadCzByProjectOrOpGuide(String projectId, String opGuideId) {
		Map<String, Object> result = Maps.newHashMap();
		if(StringUtils.isBlank(projectId) && StringUtils.isBlank(opGuideId)) {
			result.put("status", "fail");
			result.put("message", "缺少参数");
		}else {
			OpGuide opGuide = new OpGuide();
			opGuide.setId(opGuideId);
			opGuide.setProject(new Project(projectId));
			List<String> czList = opGudeService.loadCzByProjectId(opGuide);
			result.put("data", czList);
			result.put("status", "success");
		}
		return result;
	}

}
